package cn.edu.sdu.sol.intake_system.service;

import cn.edu.sdu.sol.intake_system.model.po.*;
import cn.edu.sdu.sol.intake_system.model.vo.JwtResponse;
import cn.edu.sdu.sol.intake_system.model.vo.LoginRequest;
import cn.edu.sdu.sol.intake_system.repository.AdminRepository;
import cn.edu.sdu.sol.intake_system.repository.PersonRepository;
import cn.edu.sdu.sol.intake_system.repository.UserRepository;
import cn.edu.sdu.sol.intake_system.utils.JwtUtil;
import kong.unirest.Unirest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AuthService {

    @Autowired
    UserRepository userRepository;

    @Autowired
    PersonRepository personRepository;

    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    private AdminRepository adminRepository;

    public ResponseEntity<JwtResponse> login(LoginRequest loginRequest) {

        //从请求体中获取用户名和密码
        String studentNum = loginRequest.getStudentNum();
        String password = loginRequest.getPassword();

        String name = authenticate(studentNum, password);
//        System.out.println(name);

        //统一认证通过
        if (name != null) {

            //搜寻数据库中是否有该用户信息
            Optional<SysUser> op = userRepository.findUserByStudentNum(studentNum);
            SysUser u = new SysUser();
            PersonInf p = new PersonInf();
            AdminInf a = new AdminInf();
            //不存在
            if (op.isEmpty()) {
                p.setName(name);
                //无法从统一认证登录中获取学院信息
                personRepository.saveAndFlush(p);
                u.setStudentNum(studentNum);
                u.setName(name);
                u.setRole(UserType.COMMON);
                u.setStatus(UserStatus.ACTIVE);
                u.setPersonInf(p);
                userRepository.saveAndFlush(u);

            } else {
                u = op.get();
                //判断是否为管理员的首次登陆 (管理员身份数据库改！)
                if (u.getRole() == UserType.ADMIN) {
                    if (u.getAdminInf() == null) {

                        adminRepository.saveAndFlush(a);
                        u.setAdminInf(a);
                        userRepository.saveAndFlush(u);
                    }
                }
            }

            // 生成JWT令牌
            String token = jwtUtil.generateToken(studentNum);

            // 创建JwtResponse对象并设置令牌
            JwtResponse jwtResponse = new JwtResponse();
            jwtResponse.setToken(token)
                    .setName(name)
                    .setStudentNum(studentNum)
                    .setRole(u.getRole());


            // 返回包含JWT令牌的响应实体
            return ResponseEntity.ok(jwtResponse);
        } else {
            // 验证失败的处理逻辑
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

    public String authenticate(String username, String password) {

        String baseURL = "https://pass.sdu.edu.cn/";

        // 获取ticket
        String ticket = Unirest.post(baseURL + "cas/restlet/tickets").
                body("username=" + username + "&password=" + password).asString().getBody();
        if (!ticket.startsWith("TGT")) {
            return null;
//                throw new RuntimeException("ticket should start with TGT");
        }

        // 获取sTicket
        String sTicket = Unirest.post(baseURL + "cas/restlet/tickets/" + ticket).
                body("service=https://service.sdu.edu.cn/tp_up/view?m=up").asString().getBody();
        //System.out.println("sTicket: " + sTicket);
        if (!sTicket.startsWith("ST")) {
            return null;
//                throw new RuntimeException("sTicket should start with ST");
        }

        // 获取姓名和学号
        String validationResult = Unirest.get(baseURL + "cas/serviceValidate").
                queryString("ticket", sTicket).
                queryString("service", "https://service.sdu.edu.cn/tp_up/view?m=up").asString().getBody();

        Document document = Jsoup.parse(validationResult);
        String name = document.getElementsByTag("cas:USER_NAME").text(); //获取学生姓名
        String studentNum = document.getElementsByTag("cas:").text(); //获取学生学号
//            System.out.println(name);

        return name;
    }


}
